import { _decorator, Component, Label, Node, Sprite, SpriteFrame, UITransform } from 'cc';
import { Hero, LocationStrList } from '../entity/Hero';
import { EventManager } from '../event/EventManager';
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import HeroApi from '../api/HeroApi';
import { SelectHero } from './SelectHero';
const { ccclass, property } = _decorator;

@ccclass('GroupItem')
export class GroupItem extends Component {
    @property(Node)
    close:Node
    @property(Sprite)
    headImg:Sprite
    @property(Label)
    location:Label
    @property(Node)
    selectBtn:Node
    @property(SpriteFrame)
    defaultImg:SpriteFrame
    
    public hero:Hero
  
    loc:number = 0

    start() {
        this.close.on(Node.EventType.TOUCH_END, this.onClose, this)
        this.selectBtn.on(Node.EventType.TOUCH_END, this.toSelect, this)
    }

    async setData(heroList:Hero[], loc:number){
        this.loc = loc
        
        this.hero = null
        for(let h of heroList){
            if(h.loc == this.loc){
                this.hero = h
            }
        }

        if(this.hero){
            this.close.active = true
            this.headImg.spriteFrame = await this.hero.getHeadImg()
            let transForm = this.headImg.node.getComponent(UITransform)
            transForm.width = 150
            transForm.height = 150
            this.location.string = this.hero.name
        } else {
            this.close.active = false
            this.headImg.spriteFrame = this.defaultImg
            let transForm = this.headImg.node.getComponent(UITransform)
            transForm.width = 82
            transForm.height = 82
            this.location.string = LocationStrList[this.loc]
        }

        
    }

    async onClose(){
        await UIManager.instance.showLoading()
        let res = await HeroApi.Execute({
            op: 8,
            hid: this.hero.id,
            seat: this.loc
        })
        UIManager.instance.closeLoading()

       
      
        EventManager.instance.emit(EventManager.EventType.HeroLocationChange, 1)
    }

    async toSelect(){
        if(this.hero){
            UIManager.instance.tip('该位置已有英雄')
            return
        }

        let ui = await UIManager.instance.openUI(PrefabEnum.SelectHero)
        ui.getComponent(SelectHero).setData(this.loc)
    }

}


